import csv

import pymysql

conn = pymysql.connect(host='127.0.0.1',
                       port=3306,
                       user='root',
                       password='root',
                       db='test1',
                       charset='utf8')


def insert(user_id, item_id, cate_id, action_type, action_time, conn):
    sql = 'INSERT INTO train VALUES(%s,%s,%s,%s,%s)'

    with  conn.cursor() as cur:
        try:
            cur.execute(sql,(user_id, item_id, cate_id, action_type, action_time))
        except Exception as e :
            print(user_id, item_id, cate_id, action_type, action_time)
        conn.commit()


def write():
    f = csv.reader(open(r'C:\Users\Lenovo\Desktop\datagrand_0517\train.csv', 'r'))
    num = 0
    for i in f:
        num += 1
        if num == 1:
            continue
        user_id, item_id, cate_id, action_type, action_time = i
        action_time = int(action_time)
        insert(user_id, item_id, cate_id, action_type, action_time, conn)
        if num % 500 == 0:
            print(num)


if __name__ == '__main__':
    write()
